<template>
  <div class="mc-image-upload">
    <!-- 增加编辑器内的体验 -->
    <el-upload v-if="canUpload" :file-list="fileList" v-bind="$attrs" v-on="$listeners" :action="uploadUrl"
              :http-request="uploadRequest"
               :on-preview="viewPic" :on-remove="removePic" :on-success="successUpload" :list-type="listType">
      <i class="el-icon-upload" v-if="mcShowUploadIcon"></i><slot></slot>
    </el-upload>
    <el-upload disabled v-else :file-list="fileList" v-bind="$attrs" v-on="$listeners" :action="uploadUrl"
               :on-preview="viewPic" :on-remove="removePic" :on-success="successUpload" :list-type="listType">
      <i @click="assist" class="el-icon-upload" v-if="mcShowUploadIcon"></i><slot></slot>
    </el-upload>

    <mc-dialog :visible.sync="dialogVisible" top="10px" v-bind="mcDialog">
      <img style="max-height:100%;max-width:100%" :src="dialogImageUrl" alt="">
    </mc-dialog>
  </div>
</template>

<script>
  import McDialog from "./McDialog.vue";
  export default {
    name: 'mc-image-upload',
    data () {
      return {
        //实现了双向绑定 坑爹的 不给值就报空指针
        fileList : this.buildFileList(this.value),
        dialogVisible:false,
        dialogImageUrl:"",
        uploadUrl: this.$magicaltool.request.util.wrapMagicalOpenapiUrl(this.action)||"",
        canUpload:window.iframeUi?false:true,

      }
    },
    components:{
      McDialog
    },
    props:{
      /*自动计算服务名*/
      'mcCalcCtx':{type:Boolean,default:true},
      'action':{type:String,default:""},
      //此处的value 就是父亲的v-model
      'value' : {type:String},
      'listType': {type:String,default:'picture-card'},
      //是否显示上传图标
      'mcShowUploadIcon':{type:Boolean,default:true},
      //是否单文件模式，后面上传的都覆盖
      'mcSingleFile':{type:Boolean,default:false},
      'mcDialog':{type:Object,default:function(){ return {width:'70%',top:"15vh",modal:true} }},

    },
    watch:{
      //发现变更，把父组件的v-model给改变
      fileList(newValue){
        var arr = [];
        if(newValue){
          for(var i=0;i<newValue.length;i++){
            arr.push(this.$magicaltool.request.util.unwrapServerName(newValue[i].url,this.mcCalcCtx));
          }
        }
        var url = arr.join(",")
        this.$emit("input",url)
      },
      value(newValue){
        this.fileList = this.buildFileList(newValue)
      }
    },
    mounted () {
      if(window.iframeUi&&window.iframeUi.jsonFactory){
        this.$nextTick(function(){
          var dragMcPane = window.iframeUi.jsonFactory.api().pubGetDragMcPaneName();
          var magicalCoderIdAttrName = window.iframeUi.jsonFactory.api().getMagicalCoderIdAttrName();
          var container = $("#magicalDragSceneGhost").length>0?$("#magicalDragSceneGhost") : $("#magicalDragScene");
          container.find(".mc-image-upload").each(function(idx,item){
            var firstDiv = $(this).children().first();
            if(firstDiv.length>0){//elementui 你为啥开始不创建这个结构烦死
              firstDiv.removeAttr(magicalCoderIdAttrName);
            }
          })
          //虚拟dom转化为真实dom后触发 这样动态新增的结构里 仍然可以被拖拽
          //window.iframeUi.magicalApi.addApiTask({methodName:"refreshDragEvent"});
        })
      }
    },
    methods:{
      isPic(src){
        if(src){
         var arr = src.split("?");
         var reg=/(.*)\.(bmp|jpg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp|avif|apng)$/;
         if(reg.test(arr[0])){
          return true;
         }
        }
        return false;
      },
      assist(){
        this.$notify({type:"warning",message:"设计阶段暂停上传，您可以在预览界面体验",position:"bottom-right"})
      },
      getFileName(url){
        if(url){
          var pos1 = url.lastIndexOf('/');
          var pos2 = url.lastIndexOf('\\');
          var pos  = Math.max(pos1, pos2)
          if( pos<0 )
            return url;
          else
            var name = url.substring(pos+1);
          if(name.indexOf("?")!=-1){
            return name.split("?")[0];
          }
          return name;
        }
        return "";
      },
      buildFileList:function(v){
        var request = this.$magicaltool.request;
        var list = [];
        if(v){
          var arr = v.split(",");
          for(var i=0;i<arr.length;i++){
            var url = request.util.wrapServerName(arr[i],this.mcCalcCtx);
            list.push({name:this.getFileName(url),url:url});
          }
        }
        return list;
      },
      viewPic:function(file){
        this.dialogImageUrl = file.url;
        if(this.isPic(file.url)){
          this.dialogVisible = true;
        }else{
            var request = this.$magicaltool.request;
            request.openUtil.download({href:file.url,download:file.name})
            this.dialogVisible = false;
        }
      },
      removePic:function(file, fileList){
        this.fileList = fileList;
        this.$nextTick(()=>{
          this.$emit("change",{trigger:'remove',value:this.value,file:file,fileList:fileList});
        })
      },
      uploadRequest:function(param){
          let fileObj = param.file;
              let form = new FormData();
              form.append('file', fileObj);
              this.$magicaltool.request.axios(
                {
                  $vue:this,method:"post",url:this.uploadUrl,data:form,
                  onUploadProgress: function (event) {
                     console.log("---")
                     param.file.percent = event.loaded / event.total * 100;
                     param.onProgress(param.file);
                   }
                 }
               ).then(res => {
                 this.successUpload(res,null,this.fileList);
               }).catch(res => {
                 console.log('长传失败',res)
               });
      },
      successUpload:function(res,file,fileList){
        var realName = "";
        var request = this.$magicaltool.request;
        if(typeof res['code']!== 'undefined' && res.code===0){
          var data = res.data;
          if(data){
            realName = data.name;
            data.url = request.util.wrapServerName(data.url,this.mcCalcCtx);
            data.name = this.getFileName(data.url);
            if(this.mcSingleFile){
              this.fileList=[data];
            }else {
              this.fileList.push(data);
            }
          }
          this.$message({type:"success",message:"上传成功"});
        }else{
          if(res['desc']){
            this.$message(res.desc);
          }else{
            var url = request.util.wrapServerName(res,this.mcCalcCtx);
            var data = {name:this.getFileName(url),url:url};
            if(this.mcSingleFile){
              this.fileList=[data];
            }else {
              this.fileList.push(data)
            }
          }
        }
        this.$nextTick(()=>{
          //老的方法 暂时兼容 后续去掉 TODO
          this.$emit("on-success",res);
          //新的
          this.$emit("change",{trigger:'upload',value:this.value,name:realName,res:res,file:file,fileList:fileList});
        })
      }
    }
  }
</script>

<style lang="scss">
  .mc-image-upload>div>.el-upload--picture-card{
    width:100%;
    height:100%;
    display:flex;
    align-items:center;
    justify-content:center;
  }
  .mc-image-upload>div:not(.el-dialog__wrapper){
    height:100%;
  }
</style>
